#include "google_reader.hpp"
#include "web_client.hpp"

#include <QMap>
#include <QDebug>
#include <QBuffer>
#include <QRegExp>
#include <QStringList>
#include <QNetworkCookieJar>
#include <QDateTime>

QString GoogleReader::SOURCE = "socialbox";
QString GoogleReader::ROOT_URL = "www.google.com";
QString GoogleReader::LOGIN_URL = "https://" + ROOT_URL + "/accounts/ClientLogin";


Result::Result()
{
    status = 0;
}

Result::~Result(){
}

GoogleReader::GoogleReader(QString username, QString password, WebClient::SynchronizationMode mode)
{
    _username = username;
    _password = password;
    _webClient = new WebClient(mode);
    _buffers = new QMap<QString, QBuffer*>();
    _results = new QMap<QString, Result*>();
    connect(_webClient, SIGNAL(httpRequestFinished(QString,int,QIODevice*)), this, SLOT(httpRequestFinished(QString,int,QIODevice*)));
}

GoogleReader::~GoogleReader()
{
    delete _webClient;
    delete _buffers;
    delete _results;
}

int GoogleReader::_parseLogin(QIODevice *data)
{
    QStringList results;
    QString SID;
    QNetworkCookie cookie;
    QNetworkCookieJar *cookiejar = _webClient->cookieJar();
    QUrl cookieUrl = QUrl("http://" + ROOT_URL);
    QList<QNetworkCookie> cookies = cookiejar->cookiesForUrl(cookieUrl);
    QDateTime expirationDate = QDateTime::currentDateTime();

    results = QString(((QBuffer*)data)->data()).split('\n').filter(QRegExp("SID=(\\w*)"));
    // We remove all the previously stored cookies.
    foreach(QNetworkCookie c, cookies){
        if (c.name() == "SID")
            cookies.removeOne(c);
    }

    if (results.size() > 0){
        SID = results[0].replace("SID=", "");
        cookie = QNetworkCookie("SID", SID.toUtf8());
        expirationDate = expirationDate.addMonths(6);
        cookie.setExpirationDate(expirationDate);
        cookie.setPath("/");
        cookie.setDomain(".google.com");
        cookies.append(cookie);
        cookiejar->setCookiesFromUrl(cookies, cookieUrl);
    }
/*
    foreach (QNetworkCookie c, _webClient->cookieJar()->cookiesForUrl(cookieUrl))
        qDebug() << "Cookie:" << c.toRawForm();
*/
    return SID.isEmpty() ? -1 : 0;
}

void GoogleReader::httpRequestFinished(QString url, int status, QIODevice *data)
{
    Result *result;
    if (_buffers->contains(url)){
        if (url == LOGIN_URL){
            result = new Result();
            result->status = _parseLogin(data);
            emit loginFinished(result->status);
        }
    }

    // Buffers have been allocated by GoogleReader itself
    // We clean everything when request has been handled.
    _buffers->remove(url);
    delete data;
    if (_webClient->synchronizationMode == WebClient::Synchronous)
        _results->insert(url, result);
    else
        delete result;
}

int GoogleReader::login(QString username, QString password)
{
    _username = username;
    _password = password;
    return login();
}

int GoogleReader::login()
{
    QMap<QString, QString> args = QMap<QString, QString>();
    int status = 0;
    if (!_username.isEmpty()){
        _buffers->insert(LOGIN_URL, new QBuffer());
        args["Email"] = _username;
        args["Passwd"] = _password;
        args["Service"] = "reader";
        args["Source"] = SOURCE;
        args["Continue"] = ROOT_URL;
        _webClient->post(LOGIN_URL, args, _buffers->value(LOGIN_URL));
        if (_webClient->synchronizationMode == WebClient::Synchronous){
            if (_results->contains(LOGIN_URL)){
                status = _results->value(LOGIN_URL)->status;
                _results->remove(LOGIN_URL);
            }
        }
    }
    else
        status = -1;
    return status;
}
